package com.sunwayworld.baseline.framework.utils;

import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoCredential;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.sunwayworld.framework.context.ApplicationContextHelper;
import com.sunwayworld.framework.utils.ObjectUtils;
import org.springframework.core.env.Environment;
import org.springframework.data.mongodb.core.MongoTemplate;

import java.util.HashMap;
import java.util.Map;

public class MongoDBUtil {

    public static Map<String,MongoTemplate> mongoTemplates;
    public static MongoTemplate getMongoTemplate(String dbName){
        Environment env = ApplicationContextHelper.getEnvironment();
        String username = env.getProperty("spring.data.mongodb.username");
        String password = env.getProperty("spring.data.mongodb.password");
        String host = env.getProperty("spring.data.mongodb.host");
        String port = env.getProperty("spring.data.mongodb.port");
        String connectionString = "mongodb://"+host+":"+port+"/"+dbName;
        if (ObjectUtils.isEmpty(mongoTemplates)) mongoTemplates = new HashMap<>();
        if (mongoTemplates.containsKey(connectionString)){
            return mongoTemplates.get(connectionString);
        }else {
            //1.创建链接
            if (ObjectUtils.isEmpty(username) || ObjectUtils.isEmpty(password)) return null;
            MongoCredential mongoCredential = MongoCredential.createScramSha256Credential(username, dbName, password.toCharArray());
            ConnectionString connString = new ConnectionString(connectionString);
            MongoClientSettings settings = MongoClientSettings.builder()
                    .applyConnectionString(connString)
                    .credential(mongoCredential)
                    .retryWrites(true)
                    .build();
            MongoClient mongoClient = MongoClients.create(settings);
            MongoTemplate mongoTemplate = new MongoTemplate(mongoClient, dbName);
            mongoTemplates.put(connectionString,mongoTemplate);
            return mongoTemplate;
        }
    }
}
